package wiki.tools.vidition.droid;

import java.io.File;
import java.util.ArrayList;
import wiki.tools.vidition.droid.util.DbHelper;
import wiki.tools.vidition.droid.util.bean.BookMarkBean;
import wiki.tools.vidition.droid.util.bean.NoteBookBean;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Wiki extends Activity implements OnClickListener {
	
	private EditText searchContent_etxt;
	private Button category_btn;
	private Button news_btn;
	private Button bookmark_btn;
	private Button language_btn;
	private Button notebook_btn;
	private Button search_btn;
	private LinearLayout news_linLayout;
	private Context context;
	private TextView itemDesc_textview;
	private RadioGroup language_radiogroup;
	private static final String[] itemdesc = { " Category", "     Languages",
			"          Bookmarks", "                  Notebook",
			"                             Articles" };
	private TextView tip_textview;
	public static String packName;

	private ArrayList<BookMarkBean> bookmark;
	private ArrayList<NoteBookBean> note;

	private ListView bookMark_listView;

	public static final int DATA_NULL = 9;
	private RelativeLayout cartoon;

	private ImageButton highlyrecommended_ibtn;
	private ImageButton popularranking_ibtn;
	private ListView notebook_listview;

	private static final int ALPHA_CARTOON = 10;
	private AlphaAnimation animation;

	private DbHelper mDbHelper;

	private int current;
	private int next;

	private LinearLayout linearLayout;
	private TranslateAnimation downAnimation = new TranslateAnimation(0, 0,
			430, 480);
	private TranslateAnimation upAnimation = new TranslateAnimation(0, 0, 480,
			430);
	private Button downButton;
	private Button upButton;
	private EditText view;

	private ListView category_listview;

	private static final String[] categroy_String = { "     Culture",
			"     Geography", "     Health", "     History",
			"     Mathematics", "     Science", "     Philosophy",
			"     Religion", "     Society", "     Technology" };

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		com.vidition.droid.util.CheckUpdateService.checkUpdate(this,"http://updates.bzmob.com/UpdateService.ashx?method=getversioninfo2&name=%s&versioncode=%d");
		mDbHelper = new DbHelper(this);
		mDbHelper.open();
		packName = getPackageName();
		context = Wiki.this;
		getView();
		animation = new AlphaAnimation(1.0f, 0.2f);
		animation.setRepeatCount(0);
		animation.setDuration(1500);
		animation.setAnimationListener(animationListener);
		next = current = R.id.news;
		new Thread(fetedata).start();

	}

	private void getView() {

		category_listview = (ListView) findViewById(R.id.main_category_listview);

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,
				android.R.layout.simple_list_item_1, categroy_String);

		category_listview.setAdapter(adapter);

		category_listview.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent(context, ShowCategory.class);
				intent.putExtra(Intent.EXTRA_TITLE, categroy_String[position]
						.trim());
				startActivity(intent);
			}
		});

		cartoon = (RelativeLayout) findViewById(R.id.main_cartoon);

		notebook_listview = (ListView) findViewById(R.id.notemark_listview);

		highlyrecommended_ibtn = (ImageButton) findViewById(R.id.main_highlyrecommended);
		popularranking_ibtn = (ImageButton) findViewById(R.id.main_popularranking);

		highlyrecommended_ibtn.setOnClickListener(newsOnClickListener);
		popularranking_ibtn.setOnClickListener(newsOnClickListener);

		bookMark_listView = (ListView) findViewById(R.id.bookmark_listview);

		tip_textview = (TextView) findViewById(R.id.tip);

		language_radiogroup = (RadioGroup) findViewById(R.id.language_content);

		itemDesc_textview = (TextView) findViewById(R.id.itemdes);

		news_linLayout = (LinearLayout) findViewById(R.id.news_content);

		category_btn = (Button) findViewById(R.id.category);
		news_btn = (Button) findViewById(R.id.news);
		language_btn = (Button) findViewById(R.id.language);
		notebook_btn = (Button) findViewById(R.id.notebook);
		bookmark_btn = (Button) findViewById(R.id.bookmark);

		searchContent_etxt = (EditText) findViewById(R.id.content);

		searchContent_etxt.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {

				if (event.getAction() == 0) {
					switch (keyCode) {
					case KeyEvent.KEYCODE_ENTER:
						String temp = searchContent_etxt.getText().toString()
								.trim();
						if (TextUtils.isEmpty(temp)) {
							Toast.makeText(context,
									"Search Content is not empty!",
									Toast.LENGTH_SHORT).show();
						} else {
							temp = temp.trim();
							mDbHelper.saveHigh(temp);
							Intent intent = new Intent(Wiki.this,
									SearchRSS.class);
							intent.putExtra(Intent.EXTRA_TITLE, temp);
							startActivityForResult(new Intent(intent),
									Intent.FILL_IN_DATA);
						}
						break;

					default:
						break;
					}

				}
				return false;
			}

		});

		search_btn = (Button) findViewById(R.id.search);

		category_btn.setOnClickListener(this);
		language_btn.setOnClickListener(this);
		news_btn.setOnClickListener(this);
		notebook_btn.setOnClickListener(this);
		bookmark_btn.setOnClickListener(this);
		search_btn.setOnClickListener(onClickListener);

		linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
		downButton = (Button) findViewById(R.id.down);
		upButton = (Button) findViewById(R.id.up);

		downButton.setOnClickListener(this);
		upButton.setOnClickListener(this);
		downAnimation.setDuration(50);
		upAnimation.setDuration(50);
		downAnimation.setAnimationListener(new AnimationListener() {

			public void onAnimationEnd(Animation animation) {

				linearLayout.setVisibility(View.GONE);
				upButton.setVisibility(View.VISIBLE);
			}

			public void onAnimationRepeat(Animation animation) {

			}

			public void onAnimationStart(Animation animation) {

			}

		});
		upAnimation.setAnimationListener(new AnimationListener() {

			public void onAnimationEnd(Animation animation) {
				upButton.setVisibility(View.GONE);

			}

			public void onAnimationRepeat(Animation animation) {

			}

			public void onAnimationStart(Animation animation) {
			}

		});

	}

	Runnable fetedata = new Runnable() {
		public void run() {
			handler.sendEmptyMessageDelayed(ALPHA_CARTOON, 2000);
		}
	};

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.category:
			tip_textview.setText("");
			current = R.id.category;
			itemDesc_textview.setText(itemdesc[0]);
			news_linLayout.setVisibility(View.GONE);
			language_radiogroup.setVisibility(View.GONE);
			bookMark_listView.setVisibility(View.GONE);
			notebook_listview.setVisibility(View.GONE);
			category_listview.setVisibility(View.VISIBLE);
			break;

		case R.id.news:
			tip_textview.setText("");
			current = R.id.news;
			itemDesc_textview.setText(itemdesc[4]);
			language_radiogroup.setVisibility(View.GONE);
			bookMark_listView.setVisibility(View.GONE);
			notebook_listview.setVisibility(View.GONE);
			category_listview.setVisibility(View.GONE);
			news_linLayout.setVisibility(View.VISIBLE);
			break;

		case R.id.language:
			tip_textview.setText("");
			current = R.id.language;
			itemDesc_textview.setText(itemdesc[1]);
			news_linLayout.setVisibility(View.GONE);
			bookMark_listView.setVisibility(View.GONE);
			notebook_listview.setVisibility(View.GONE);
			category_listview.setVisibility(View.GONE);
			language_radiogroup.setVisibility(View.VISIBLE);
			break;

		case R.id.notebook:
			tip_textview.setText("");
			current = R.id.notebook;
			itemDesc_textview.setText(itemdesc[3]);
			news_linLayout.setVisibility(View.GONE);
			language_radiogroup.setVisibility(View.GONE);
			bookMark_listView.setVisibility(View.GONE);
			category_listview.setVisibility(View.GONE);
			notebook_listview.setVisibility(View.VISIBLE);
			doNoteBook();
			break;

		case R.id.bookmark:
			tip_textview.setText("");
			current = R.id.bookmark;
			itemDesc_textview.setText(itemdesc[2]);
			news_linLayout.setVisibility(View.GONE);
			language_radiogroup.setVisibility(View.GONE);
			notebook_listview.setVisibility(View.GONE);
			category_listview.setVisibility(View.GONE);
			bookMark_listView.setVisibility(View.VISIBLE);
			doBookMark();
			break;

		case R.id.down:
			linearLayout.startAnimation(downAnimation);

			break;
		case R.id.up:
			linearLayout.setVisibility(View.VISIBLE);
			linearLayout.startAnimation(upAnimation);

			break;
		}
		changeButtonBackground(current);
	}

	private void doNoteBook() {
		note = mDbHelper.getAllNoteBook();
		String[] s = new String[note.size()];
		if (0 != note.size()) {
			for (int i = 0; i < note.size(); i++) {
				s[i] = note.get(i).title;
			}
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_1, s);
			notebook_listview.setAdapter(adapter);
			notebook_listview.setClickable(true);
			notebook_listview.setScrollingCacheEnabled(false);
			notebook_listview.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					Intent intent = new Intent(context, NoteBook.class);
					intent.putExtra(Intent.EXTRA_TITLE,
							note.get(position).title);
					startActivityForResult(intent, Intent.FILL_IN_DATA);
				}
			});
		} else {
			notebook_listview.setAdapter(null);
			handler.sendEmptyMessage(20);
		}
	}

	private void doBookMark() {
		bookmark = mDbHelper.getAllBookMark();
		if (0 != bookmark.size()) {
			String[] s = new String[bookmark.size()];

			for (int i = 0; i < bookmark.size(); i++) {
				s[i] = bookmark.get(i).title;
			}
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,
					android.R.layout.simple_list_item_1, s);
			bookMark_listView.setAdapter(adapter);
			bookMark_listView.setClickable(true);
			bookMark_listView.setFocusable(true);
			bookMark_listView.setScrollingCacheEnabled(false);
			bookMark_listView.setOnItemClickListener(onItemSelectedListener);
		} else {
			bookMark_listView.setAdapter(null);
			handler.sendEmptyMessage(DATA_NULL);
		}
	}

	OnItemClickListener onItemSelectedListener = new OnItemClickListener() {

		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			Intent intent = new Intent(context, ShowUrlActivity.class);
			intent.putExtra(Intent.EXTRA_TITLE, bookmark.get(position).title);
			intent.putExtra(Intent.EXTRA_TEXT, bookmark.get(position).body);
			startActivityForResult(intent, Intent.FILL_IN_DATA);
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (current == R.id.bookmark) {
			doBookMark();
		} else if (current == R.id.notebook) {
			doNoteBook();
		}
	}

	OnClickListener newsOnClickListener = new OnClickListener() {
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.main_highlyrecommended:
				startActivity(new Intent(context, ShowHighDetail.class));
				break;

			case R.id.main_popularranking:
				Intent intent = new Intent(context, ShowUrlActivity.class);
				intent
						.putExtra(Intent.EXTRA_TEXT,
								"http://en.m.wikipedia.org/wiki/Wikipedia:Featured_articles");
				intent.putExtra(Intent.EXTRA_TITLE, "PopularRanking");
				startActivityForResult(intent, Intent.FILL_IN_DATA);
				break;
			}
		}
	};

	OnClickListener onClickListener = new OnClickListener() {
		public void onClick(View v) {
			String temp = searchContent_etxt.getText().toString().trim();
			if (TextUtils.isEmpty(temp)) {
				Toast.makeText(context, "Search Content is not empty!",
						Toast.LENGTH_SHORT).show();
				return;
			}
			temp = temp.trim();
			mDbHelper.saveHigh(temp);
			Intent intent = new Intent(Wiki.this, SearchRSS.class);
			intent.putExtra(Intent.EXTRA_TITLE, temp);
			startActivityForResult(new Intent(intent), Intent.FILL_IN_DATA);
		}
	};

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			switch (msg.what) {
			case DATA_NULL:
				tip_textview.setText("Bookmark is empty!");
				break;

			case 20:
				tip_textview.setText("NoteBook is empty!");
				break;

			case ALPHA_CARTOON:
				cartoon.startAnimation(animation);
				break;

			default:
				break;
			}
		}
	};

	AnimationListener animationListener = new AnimationListener() {
		public void onAnimationEnd(Animation animation) {
			cartoon.setVisibility(View.GONE);
		}

		public void onAnimationRepeat(Animation animation) {
			// TODO Auto-generated method stub

		}

		public void onAnimationStart(Animation animation) {
			// TODO Auto-generated method stub

		}

	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(0, 1, 0, "Exit").setIcon(R.drawable.exit3);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.clear();
		switch (current) {
		case R.id.notebook:
			menu.add(0, 2, 0, "Add note").setIcon(R.drawable.addnewone);
		case R.id.bookmark:
			menu.add(0, 0, 0, "Delete All").setIcon(R.drawable.delete_selector);
			menu.add(0, 1, 0, "Exit").setIcon(R.drawable.exit3);
			break;
		default:
			menu.add(0, 1, 0, "Exit").setIcon(R.drawable.exit3);
			break;
		}
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case 0:
			deleteAllData(current);
			break;

		case 1:
			Wiki.this.finish();
			break;

		case 2:
			// LayoutInflater layoutInflater = (LayoutInflater) context
			// .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View e = LayoutInflater.from(context).inflate(R.layout.edit, null);

			view = (EditText) e.findViewById(R.id.addnewnote);

			new AlertDialog.Builder(context).setView(view).setTitle(
					"Input fileName:").setPositiveButton("Ok",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							String temp = view.getText().toString().trim();
							if (!TextUtils.isEmpty(temp)) {
								Intent intent = new Intent(context,
										NoteBook.class);
								intent.putExtra(Intent.EXTRA_TITLE, temp);
								Wiki.this.startActivityForResult(intent,
										Intent.FILL_IN_DATA);
							}
						}

					}).show();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void deleteAllData(int index) {
		switch (index) {
		case R.id.bookmark:
			mDbHelper.deleteAllDataBookMark();
			doBookMark();
			break;
		case R.id.notebook:
			mDbHelper.deleteAllDataNoteBook();
			doNoteBook();
			break;
		}
	}

	private void changeButtonBackground(int index) {

		if (next == index) {
			return;
		}

		switch (index) {
		case R.id.category:
			category_btn.setBackgroundResource(R.drawable.category2);
			break;

		case R.id.news:
			news_btn.setBackgroundResource(R.drawable.news2);
			break;

		case R.id.notebook:
			notebook_btn.setBackgroundResource(R.drawable.notebook2);
			break;

		case R.id.bookmark:
			bookmark_btn.setBackgroundResource(R.drawable.bookmark2);
			break;

		case R.id.language:
			language_btn.setBackgroundResource(R.drawable.languages2);
			break;
		}
		change(next);
		next = index;
	}
	

	private void change(int index) {
		switch (index) {
		case R.id.category:
			category_btn.setBackgroundResource(R.drawable.categroy);
			break;

		case R.id.news:
			news_btn.setBackgroundResource(R.drawable.icon5);
			break;

		case R.id.notebook:
			notebook_btn.setBackgroundResource(R.drawable.icon4);
			break;

		case R.id.bookmark:
			bookmark_btn.setBackgroundResource(R.drawable.icon3);
			break;

		case R.id.language:
			language_btn.setBackgroundResource(R.drawable.icon2);
			break;
		}
	}

	@Override
	protected void onDestroy() {
		File file = getCacheDir();
		if (file.exists()) {
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				for (File f : files[i].listFiles()) {
					f.delete();
				}
			}
		}
		mDbHelper.close();
		super.onDestroy();
	}

}